<template>
    <!-- 适用范围 -->
    <vab-card>
      <template #header>
        <div class="flex leve2_title">
          适用范围
        </div>
      </template>
      <template #default>
        <!-- <div class="flex width_100">
          <el-form
            label-position="left"
            label-width="110px"
            ref="rangeFormRef"
            :model="rangeForm"
            class="flex width_100"
          >
            <el-row :gutter="24" class="width_100">
              <el-col v-bind="colLay">
                <el-form-item label="限定客户范围" required>
                  :disabled="!rangeForm.use_org_id"
                  <VabSelectForm 
                    v-model="rangeForm.compositeValue" :options="checkCompositeSearch" @change="handleComposite"/>
                </el-form-item>
              </el-col>
              <el-col v-bind="colLay">
                <el-form-item label="使用客户" required>
                  {{ :disabled="!rangeForm.use_org_id" }}
                  <VabInputForm
                    placeholder="请输入"
                    v-model="rangeForm[rangeForm.compositeValue]"
                    v-if="rangeForm.compositeValue == 'customer'"
                    @input="(value) => handleChange(value, rangeForm.compositeValue)"
                  />
                  <VabSelectForm
                    v-else
                    class="width_100"
                    placeholder="请选择"
                    v-model="rangeForm[rangeForm.compositeValue]"
                    :options="selectOptions(rangeForm.compositeValue)"
                    :multiple="rangeForm.compositeValue == 'primary_group' ? true : false"
                    @change="(value) => handleChange(value, rangeForm.compositeValue)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div> -->
        <div :class="{ warn: isWarn }">
          <el-form
            :ref="(el) => (productFormRef = el)"
            :model="customerList"
            class="formData"
            v-loading="tableLoading"
          >
            <el-table border height="300px" :data="customerList">
              <el-table-column label="序号" align="center" width="60">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="customer_number" align="center">
                <template #header>
                  <span class="required_text">*</span>
                  <span>客户编码</span>
                </template>
                <template #default="{ row, $index }">
                  <el-form-item prop="customer_number">
                    <CustomLazySelect
                      :type="2"
                      :clearable="false"
                      v-model="row.customer_number"
                      @LazyChange="(item: any) => {
                        productQuerySearch(item, $index)
                      }
                        "
                    />
                    <span class="error" v-if="!row.customer_number">客户编码不能为空！</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="customer_name" align="center">
                <template #header>
                  <span class="required_text">*</span>
                  <span>客户名称</span>
                </template>
                <template #default="{ row, $index }">
                  <el-form-item prop="customer_name">
                    <CustomLazySelect
                      :type="1"
                      :clearable="false"
                      v-model="row.customer_name"
                      @LazyChange="(item: any) => {
                        productQuerySearch(item, $index)
                      }
                        "
                    />
                    <span class="error" v-if="!row.customer_name">客户名称不能为空！</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="is_default" align="center">
                <template #header>
                  <span class="required_text">*</span>
                  <span>是否为默认</span>
                </template>
                <template #default="{ row }">
                  <el-form-item prop="is_default">
                    <VabSelectForm
                      :clearable="false"
                      class="width_100"
                      placeholder="请选择"
                      :options="[
                        { value: '0', label: '否' },
                        { value: '1', label: '是' },
                      ]"
                      v-model.trim="row.is_default"
                    />
                    <span class="error" v-if="!row.is_default">是否为默认为空！</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="70">
                <template #default="props">
                  <vab-icon
                    icon="add-circle-line"
                    class="icon_color"
                    @click="handleAdd(props.$index)"
                  />
                  <vab-icon
                    v-if="customerList.length > 1"
                    icon="delete-bin-5-line"
                    @click="handleRemove(props.$index)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </template>
    </vab-card>
  </template>
  
<script setup lang="ts">
defineOptions({
  name: 'CreateInfo',
})
/**
 * @props
 */
const props = defineProps({
  isWarn: {
    type: Boolean,
    default: false,
  },
  fromPage: {
    type: String,
    default: '',
  },
})
/**
 * @import
 */
import _ from 'lodash'
import { ref } from 'vue'
import CustomLazySelect from './CustomLazySelect.vue'
import { ReturnSelectOptions } from './tools'
import { ElMessageBox } from 'element-plus'
import { organization_list } from '~/src/api/dms/organization';
import { options_list } from '~/src/api/dms/options';
import { customerGroup_list } from '~/src/api/dms/customerGroup';
import { customer_optionsList } from '~/src/api/dms/customer';
/**
 * @var
 */
const colLay = {
  xs: 24,
  sm: 12,
  md: 12,
  lg: 6,
  xl: 6,
}

const proxy: any = getCurrentInstance()?.proxy
const vabSelectFormRef = ref<any>()

let rangeForm = ref<any>({
  compositeValue: '',
  type: '1',
})

const checkUseOrgID = ref<any>('')
const sreachScreen = ref<any>(null)
const rangeFormRef = ref()
const tableLoading = ref(false)

const checkCompositeSearch = [
  { value: 'customer', label: '客户' },
  { value: 'cust_type_id', label: '客户类别' },
  { value: 'primary_group', label: '客户分组' },
]

/**
 * @method
 */

const productFormRef = ref()
// 基础五个数据
const customerList = ref<any>([{ is_default: '1' }])

/**
 * @method
 */

const emit = defineEmits(['useOrgSelect'])

// 添加
const handleAdd = (i: number) => {
  customerList.value.splice(i + 1, 0, { is_default: '1' })
}
// 删除
const handleRemove = (index: number) => {
  customerList.value.splice(index, 1)
}

const handleChange = _.throttle(async (value: string, prop: string) => {
  if (!value) {
    customerList.value = [{ is_default: '1' }]
    return
  }
  tableLoading.value = true
  try {
    let res = await customer_optionsList({
      is_group: 2,
      name: prop == 'customer' ? value : '',
      cust_type_id: prop == 'cust_type_id' ? value : '',
      primary_group: prop == 'primary_group' ? value.toString() : '',
    })

    customerList.value = await res.data.map((item: any) => {
      return {
        customer_number: item.number,
        customer_name: item.name,
        customer_uid: item.uid,
        is_default: '1'
      }
    })

    setTimeout(() => {
      tableLoading.value = false
    }, 1000);

  } catch (error) {

  }
}, 500)

// 切换信用对象范围
const handleComposite = () => {
  // 清空原数据
  rangeForm.value.customer = ''
  rangeForm.value.cust_type_id = ''
  rangeForm.value.primary_group = ''
}

// 重置数据
const resetData = (value: any) => {
  customerList.value = [{ is_default: '1' }]
}
// 筛选项返回值
const selectOptions = (value: string) => {
  if (!sreachScreen.value) return
  if (!value) return
  return ReturnSelectOptions(sreachScreen.value, value)
}
//获取筛选项
const getScreen = async () => {
  try {
    let orgRes = await organization_list({}) //使用组织
    let customerTypeRes = await options_list({ modul: 'customer_category' }) //客户类别
    let customerGroupRes = await customerGroup_list({}) //客户分组

    sreachScreen.value = {
      useOrgList: orgRes.data,
      customerTypeList: customerTypeRes.data,
      customerGroupList: customerGroupRes.data,
    }

  } catch (error) {

  }
}
// 客户带出基本信息
const productQuerySearch = async (row: any, i: number) => {
  if (customerList.value.length > 1) {
    let voidNumber = false
    voidNumber = await customerList.value.some(
      (item: any) => item.customer_uid == row.uid
    )
    if (voidNumber) {
      proxy.$Message('信用对象重复,请重新选择！', 'warning')
      customerList.value[i] = { is_default: '1' }
      return
    }
  }
  customerList.value[i].customer_number = row.number
  customerList.value[i].customer_name = row.name
  customerList.value[i].customer_uid = row.uid
}

// 切换使用组织
const handleSwitchOrg = (value: string) => {

  const selectRef = vabSelectFormRef.value[0].selectRef

  if (checkUseOrgID.value && checkUseOrgID.value != value) {
    ElMessageBox.confirm(
      '切换使用组织，会清空【适用范围】和【规则详情】，请谨慎操作，是否确认',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        // 清除焦点
        selectRef.$refs.reference.blur()
        // 赋值
        rangeForm.value.use_org_id = value
        // 判断key
        checkUseOrgID.value = value
        // 清空
        customerList.value = [{}]
        // 清空适用范围筛选项
        rangeForm.value.compositeValue = ''
        handleComposite()
        // 规则范围清空
        emit('useOrgSelect', rangeForm.value.use_org_id, true)
      })
      .catch(() => {
        selectRef.$refs.reference.blur()
        rangeForm.value.use_org_id = checkUseOrgID.value
        emit('useOrgSelect', rangeForm.value.use_org_id, false)
      })
  } else {
    checkUseOrgID.value = value
    emit('useOrgSelect', rangeForm.value.use_org_id, false)
  }


}

// 获取更新数据
const getUpdateData = async (res: any) => {

  const { info, customer_list } = res
  const { name, number, level, is_enable, type, effective_end, effective_start, uid, use_org_id } = info

  // 基本信息
  rangeForm.value = {
    uid,
    name,
    number,
    is_enable,
    use_org_id,
    type: `${type}`,
    level: `${level}`,
    effective_date: [effective_start, effective_end],
  }

  customerList.value = customer_list.map((item: any) => {
    const { customer_name, customer_number, customer_uid, is_default } = item
    return {
      is_default: `${is_default}`,
      customer_uid,
      customer_number,
      customer_name,
    }
  })
}

// 重置数据
const getResetData = () => {
  rangeForm.value = { type: '1' }
  customerList.value = [{ is_default: '1' }]
}

/**
 * @实例
 */

//抛出数据
defineExpose({
  rangeFormRef,
  rangeForm,
  productFormRef,
  customerList,
  resetData,
  getUpdateData,
  getResetData,
})
onMounted(() => {
  getScreen()
})
</script>
  
<style lang="scss" scoped>
@import '../../../../components/public.scss';
@import url(./give.scss);
</style>
  